package com.youzhi.message;

import lombok.extern.slf4j.Slf4j;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class ChannelHolder {

    public static Map<String, Channel> channels = new ConcurrentHashMap<>();

    public static void addChannel(String webSocketId, Channel channel) {
        channels.put(webSocketId, channel);
    }

    /**
     * 全平台广播
     *
     * @param text
     */
    public static void broadcastAll(String text) {
        for (Channel channel : channels.values()) {
            channel.write(new TextWebSocketFrame(text));
        }
    }


    /**
     * 对指定用户进行广播
     *
     * @param webSocketId
     * @param text
     */
    public static void broadCast(String webSocketId, String text) {
        Channel channel = channels.get(webSocketId);
        if (channel != null) {
            channel.write(new TextWebSocketFrame(text));
        } else {
            log.info("webSocketId={}对应的channel不存在", webSocketId);
        }

    }


    /**
     * 移除指定的channel
     *
     * @param channel
     */
    public static void removeChannel(Channel channel) {

        AtomicReference<String> removeKey = new AtomicReference<>();
        channels.forEach((k, v) -> {
            if (v.getId().equals(channel.getId())) {
                removeKey.set(k);
                return;
            }
        });

        if (removeKey.get() != null) {
            channels.remove(removeKey.get());
            log.info("webSocket断开成功,webSocketId={}", removeKey.get());
        }

    }


}
